// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

import java.io.*;
import java.sql.ResultSet;
import java.util.ArrayList;

import common.*;
import entity.Question;

import ocsf.server.*;

/**
 * This class overrides some of the methods in the abstract 
 * superclass in order to give more functionality to the server.
 *
 * @author Omri Barda		039725890
 * @author Amit Joseph		034608547
 * @author Gilad Shpigel  	300162393
 * @author Elad Elbaz		040539959
 * @author Natali Kazav		038109401
 * @version May 2012
 */
public class EchoServer extends AbstractServer 
{
  //Class variables *************************************************
  
  /**
   * The default port to listen on.
   */
  final public static int DEFAULT_PORT = 5555;
  
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public EchoServer(int port) 
  {
    super(port);
  }

  
  //Instance methods ************************************************
  
  /**
   * This method handles any messages received from the client.
   *
   * @param msg The query received from the client.
   * @param client The connection from which the message originated.
   */
  public void handleMessageFromClient (Object msg, ConnectionToClient client)
  	{
	  Database db = null;
	  Boolean res;
	  String query = new String(msg.toString());

	  if (query.startsWith("INSERT"))
	  {
		  try 
		  { 
			  db = new Database();
			  res = db.addQuestion(query);
			 
			  if (res)
				  client.sendToClient("Question added successfully!");
			  else
				  client.sendToClient("Unable to add question!");
		  }
		  catch(Exception ex) 
		  {
			  Perror.pError("Unable to open DataBase <INSERT>");
			  try
			  {
				  client.sendToClient("Can't open DataBase <INSERT>");
			  }
			  catch (IOException e)
			  {
				  e.printStackTrace();
			  }		  
		  }
	  }
	  else if (query.startsWith("DELETE"))
	  		{
				  try 
				  {
					  db = new Database();
					  res = db.deleteQuestion(query);
					  if (res)
						  client.sendToClient("Question deleted successfully!");
					  else
						  client.sendToClient("Unable to delete question!");
				  }
				  catch(Exception ex) 
				  {
					  Perror.pError("Unable to open DataBase <DELETE>");
					  try
					  {
						  client.sendToClient("Can't open DataBase <DELETE>");
					  }
					  catch (IOException e)
					  {
						  e.printStackTrace();
					  }		  
				  }
	  		}
	  		else if (query.startsWith("SELECT"))
	  			{
			  		  try 
					  {
						  db = new Database();
						  ResultSet qrs = db.getQuestion(query);
						  if (qrs == null)
							  client.sendToClient("Unable to get question!");
						  else
						  { 
						  	Question Q=null;
							  ArrayList<Question> questionArray=new ArrayList<Question>(); 
							  while(qrs.next())
						 		{
									 Q = new Question(qrs.getString(1),qrs.getString(2),qrs.getString(3),qrs.getString(4),qrs.getString(5),qrs.getString(6),qrs.getString(7),qrs.getString(8),qrs.getString(9));
									 questionArray.add(Q);
								} 
							  qrs.close();
							  client.sendToClient(questionArray.toString());
						  }
					  }
					  catch(Exception ex) 
					  {
						  Perror.pError("Unable to open DataBase <GET>");
						  try
						  {
							  client.sendToClient("Can't open DataBase <GET>");
						  }
						  catch (IOException e)
						  {
							  e.printStackTrace();
						  }		  
					  }
	  			}
	}
	
  
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server starts listening for connections.
   */
  protected void serverStarted()
  {
    System.out.println
      ("Server listening for connections on port " + getPort());
  }
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server stops listening for connections.
   */
  protected void serverStopped()
  {
    System.out.println
      ("Server has stopped listening for connections.");
  }
  
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of 
   * the server instance (there is no UI in this phase).
   *
   * @param args[0] The port number to listen on.  Defaults to 5555 
   *          if no argument is entered.
   */
  public static void main(String[] args) 
  {
    int port = 0; //Port to listen on

    try
    {
      port = Integer.parseInt(args[0]); //Get port from command line
    }
    catch(Throwable t)
    {
      port = DEFAULT_PORT; //Set port to 5555
    }
	
    EchoServer sv = new EchoServer(port);
    
    try 
    {
      sv.listen(); //Start listening for connections
    } 
    catch (Exception ex) 
    {
      System.out.println("ERROR - Could not listen for clients!");
    }
  }
}
//End of EchoServer class
